package cn.edu.zafu.bigdata.lmr;

import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) {
        try {
            // 创建服务器端的ServerSocket，监听端口号1234
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("Server is running and waiting for client connection...");

            // 服务器无限循环，等待客户端的连接
            while (true) {
                // 等待接受客户端的连接，此方法会阻塞，直到一个连接建立
                Socket socket = serverSocket.accept();
                System.out.println("Client connected.");

                // 获取输入流，并创建相应的输入流对象
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                // 获取输出流，并创建相应的输出流对象
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                // 读取客户端发送的消息
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("Client says: " + inputLine);
                    // 将消息回送给客户端
                    out.println("Server received: " + inputLine);
                }

                // 关闭连接
                in.close();
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}